import router from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { filterAsyncRouter } from '@/store/modules/permission'


NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - ' + Config.title
  }
  NProgress.start()
    // next()
  if (localStorage.getItem('tokenValue')) {
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      // if (store.getters.addRouters.length === 0) {
      //   loadMenus(next, to)
      // } else {
      // console.log('to', to)
      next()
        // }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})
export const loadMenus = (next, to) => {
  console.log('to2', to)

  // let res = [{
  //       path: '/dashboard',
  //       name: "dashboard",
  //       component: () =>
  //         import ("@/views/home"),
  //       meta: { title: '首页', }
  //     },
  //     {
  //       path: '/addform',
  //       name: "addform",
  //       component: () =>
  //         import ("@/views/addform/index"),
  //       meta: { title: '表单', }
  //     },
  //   ]
  // buildMenus().then(res => {
  const sdata = JSON.parse(JSON.stringify(router.constantRouterMap))
  const rdata = JSON.parse(JSON.stringify(router.constantRouterMap))

  const sidebarRoutes = sdata
  const rewriteRoutes = rdata
    // const sidebarRoutes = filterAsyncRouter(sdata)
    // const rewriteRoutes = filterAsyncRouter(rdata, false, true)
  rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })

  store.dispatch('GenerateRoutes', rewriteRoutes).then(() => { // 存储路由
    router.addRoutes(rewriteRoutes) // 动态添加可访问路由表
    next({...to, replace: true })
  })
  store.dispatch('SetSidebarRouters', sidebarRoutes)
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
